import os
import sys
from datetime import timedelta
from pathlib import Path

import psutil
from django import setup

# 将项目路径添加到系统搜寻路径当中，查找方式为从当前脚本开始，找到要调用的django项目的路径
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'django_site.settings')
setup()

from django.utils import timezone
from buckets.models import Bucket


# 0 */12 * * * python3 /home/uwsgi/iharbor/scripts/run_update_bucket_size.py >> /var/log/iharbor/run_update_bucket_size.log

def get_cmd_name():
    cmd_name = sys.argv[0]
    li = cmd_name.rsplit('/', maxsplit=1)
    if len(li) == 1:
        cmd_name = li[0]
    else:
        cmd_name = li[1]

    return cmd_name


def check_cmd_run():
    """
    检测系统中是否存在该程序进程
    """
    pid_self = os.getpid()
    pid_list = psutil.pids()
    if pid_self in pid_list:  # remove self pid
        pid_list.remove(pid_self)

    cmd_name = get_cmd_name()
    for pid in pid_list:
        # 进程命令
        try:
            process_line = psutil.Process(pid).cmdline()
        except Exception as e:
            continue
        if not process_line:
            continue
        if 'python3' in process_line:
            for i in process_line:
                if cmd_name in i:
                    return True, cmd_name

    return False, None


def main():
    flag, cmd_name = check_cmd_run()
    if flag:
        print(f"{timezone.now()} - {cmd_name} is running.")
        return

    buckets = Bucket.objects.all()
    if not buckets:
        print(f"{timezone.now()} - No buckets")
        return

    count = 0
    for bucket in buckets:

        now_t = timezone.now() - timedelta(minutes=30)
        now_time_timestamp = now_t.timestamp()
        bucket_update_time_timestamp = bucket.stats_time.timestamp()
        if now_time_timestamp > bucket_update_time_timestamp:
            try:
                bucket.get_stats(now=True)
            except Exception as e:
                print(f"{timezone.now()} - {bucket.name} Failed to collect bucket statistics，error:{str(e)}")
                continue
            count += 1
    print(f"{timezone.now()} - Statistical completion. A total of buckets are collected:{count}")


if __name__ == '__main__':
    try:
        main()
    except Exception as e:
        print(f'{timezone.now()} - error: {str(e)}')
